/**
 * server-local.js
 * 后端服务主文件 - 本地文件存储版本
 * 功能：提供菜品管理API、用户认证、订单管理（使用本地JSON文件存储）
 */

const express = require('express');
const path = require('path');
const fs = require('fs');
const helmet = require('helmet');
const cors = require('cors');
const winston = require('winston');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');

const app = express();
const PORT = process.env.PORT || 3001;
const JWT_SECRET = process.env.JWT_SECRET || 'restaurant_secret_key';

// ==================== 日志配置 ====================
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    winston.format.errors({ stack: true }),
    winston.format.splat(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.printf(({ level, message, timestamp, stack }) => {
          if (stack) {
            return `${timestamp} ${level}: ${message}\n${stack}`;
          }
          return `${timestamp} ${level}: ${message}`;
        })
      )
    }),
    new winston.transports.File({ filename: 'logs/app.log' })
  ]
});

// ==================== 全局异常捕获 ====================
process.on('uncaughtException', (err) => {
  logger.error('未捕获的异常:', err);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('未处理的Promise拒绝:', reason);
});

// ==================== 中间件配置 ====================
app.use(helmet({
  contentSecurityPolicy: false,
  frameguard: false
}));

app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// ==================== 请求日志 ====================
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    logger.info(`${req.method} ${req.path} - ${res.statusCode} - ${duration}ms`);
  });
  next();
});

// ==================== 静态文件服务 ====================
const publicDir = path.resolve(__dirname, '../frontend/public');
const distDir = path.resolve(__dirname, '../frontend/dist');
const publicPath = fs.existsSync(publicDir) ? publicDir : distDir;

if (fs.existsSync(publicPath)) {
  app.use(express.static(publicPath));
  logger.info(`静态文件目录: ${publicPath}`);
} else {
  logger.warn(`静态文件目录不存在: ${publicPath}`);
}

// ==================== 数据存储配置 ====================
const dataDir = path.join(__dirname, 'data');

// 确保数据目录存在
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true });
}

// 数据文件路径
const dishesFile = path.join(dataDir, 'dishes.json');
const usersFile = path.join(dataDir, 'users.json');
const ordersFile = path.join(dataDir, 'orders.json');

// ==================== 数据操作函数 ====================
const readData = (filePath) => {
  try {
    if (!fs.existsSync(filePath)) {
      return [];
    }
    const data = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    logger.error(`读取数据文件失败: ${filePath}`, error);
    return [];
  }
};

const writeData = (filePath, data) => {
  try {
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
    return true;
  } catch (error) {
    logger.error(`写入数据文件失败: ${filePath}`, error);
    return false;
  }
};

// ==================== 数据初始化 ====================
const initData = () => {
  // 初始化用户数据
  let users = readData(usersFile);
  if (users.length === 0) {
    users = [
      { id: 1, username: '女王', password: '20031013', role: 'customer', created_at: Date.now() },
      { id: 2, username: '御厨', password: '20030215', role: 'kitchen', created_at: Date.now() }
    ];
    writeData(usersFile, users);
    logger.info('默认用户数据初始化完成');
  }

  // 初始化菜品数据
  let dishes = readData(dishesFile);
  if (dishes.length === 0) {
    dishes = [
      {
        id: 1,
        name: '宫保鸡丁',
        price: 38.00,
        description: '经典川菜，鸡肉鲜嫩，花生酥脆，酸甜微辣',
        category: '热菜',
        recipe: '1. 鸡肉切丁腌制\n2. 花生炸香备用\n3. 热锅爆炒调味\n4. 装盘上桌',
        weather_condition: 'normal',
        image_url: 'https://hpi-hub.tos-cn-beijing.volces.com/static/batch_14/1757354850592-5169.jpg',
        is_active: true,
        created_at: Date.now()
      },
      {
        id: 2,
        name: '麻婆豆腐',
        price: 28.00,
        description: '经典川菜，豆腐嫩滑，麻辣鲜香',
        category: '热菜',
        recipe: '1. 豆腐切块焯水\n2. 肉末炒香\n3. 加入豆瓣酱调味\n4. 煮制入味',
        weather_condition: 'cold',
        image_url: 'https://hpi-hub.tos-cn-beijing.volces.com/static/batch_14/1757354850592-5169.jpg',
        is_active: true,
        created_at: Date.now()
      },
      {
        id: 3,
        name: '糖醋排骨',
        price: 48.00,
        description: '酸甜可口，外酥里嫩，老少皆宜',
        category: '热菜',
        recipe: '1. 排骨切块腌制\n2. 油炸至金黄\n3. 糖醋汁收汁\n4. 撒芝麻装盘',
        weather_condition: 'normal',
        image_url: 'https://hpi-hub.tos-cn-beijing.volces.com/static/batch_14/1757354850592-5169.jpg',
        is_active: true,
        created_at: Date.now()
      }
    ];
    writeData(dishesFile, dishes);
    logger.info('默认菜品数据初始化完成');
  }

  // 初始化订单数据
  let orders = readData(ordersFile);
  if (orders.length === 0) {
    writeData(ordersFile, []);
    logger.info('默认订单数据初始化完成');
  }
};

// 初始化数据
initData();

// ==================== JWT认证中间件 ====================
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: '访问令牌缺失' });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ error: '令牌无效' });
    }
    req.user = user;
    next();
  });
};

// ==================== API路由 ====================

// 用户登录
app.post('/api/login', (req, res) => {
  try {
    const { username, password, role } = req.body;
    
    if (!username || !password || !role) {
      return res.status(400).json({ error: '用户名、密码和角色不能为空' });
    }

    const users = readData(usersFile);
    const user = users.find(u => u.username === username && u.password === password && u.role === role);

    if (!user) {
      return res.status(401).json({ error: '用户名、密码或角色错误' });
    }

    const token = jwt.sign(
      { id: user.id, username: user.username, role: user.role },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        role: user.role
      }
    });
  } catch (error) {
    logger.error('登录错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 获取所有菜品
app.get('/api/dishes', (req, res) => {
  try {
    const dishes = readData(dishesFile);
    res.json(dishes);
  } catch (error) {
    logger.error('获取菜品列表错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 根据ID获取菜品
app.get('/api/dishes/:id', (req, res) => {
  try {
    const dishId = parseInt(req.params.id);
    const dishes = readData(dishesFile);
    const dish = dishes.find(d => d.id === dishId);

    if (!dish) {
      return res.status(404).json({ error: '菜品不存在' });
    }

    res.json(dish);
  } catch (error) {
    logger.error('获取菜品详情错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 创建新菜品
app.post('/api/dishes', authenticateToken, (req, res) => {
  try {
    if (req.user.role !== 'kitchen') {
      return res.status(403).json({ error: '权限不足' });
    }

    const { name, price, description, category, recipe, weather_condition, image_url } = req.body;

    if (!name || !price) {
      return res.status(400).json({ error: '菜品名称和价格不能为空' });
    }

    const dishes = readData(dishesFile);
    const newDish = {
      id: dishes.length > 0 ? Math.max(...dishes.map(d => d.id)) + 1 : 1,
      name,
      price: parseFloat(price),
      description: description || '',
      category: category || '',
      recipe: recipe || '',
      weather_condition: weather_condition || 'normal',
      image_url: image_url || '',
      is_active: true,
      created_at: Date.now(),
      updated_at: null
    };

    dishes.push(newDish);

    if (writeData(dishesFile, dishes)) {
      res.status(201).json({ message: '菜品创建成功', dish: newDish });
    } else {
      res.status(500).json({ error: '保存菜品失败' });
    }
  } catch (error) {
    logger.error('创建菜品错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 更新菜品
app.put('/api/dishes/:id', authenticateToken, (req, res) => {
  try {
    if (req.user.role !== 'kitchen') {
      return res.status(403).json({ error: '权限不足' });
    }

    const dishId = parseInt(req.params.id);
    const { name, price, description, category, recipe, weather_condition, image_url, is_active } = req.body;

    const dishes = readData(dishesFile);
    const dishIndex = dishes.findIndex(d => d.id === dishId);

    if (dishIndex === -1) {
      return res.status(404).json({ error: '菜品不存在' });
    }

    // 更新菜品信息
    dishes[dishIndex] = {
      ...dishes[dishIndex],
      name: name || dishes[dishIndex].name,
      price: price ? parseFloat(price) : dishes[dishIndex].price,
      description: description !== undefined ? description : dishes[dishIndex].description,
      category: category !== undefined ? category : dishes[dishIndex].category,
      recipe: recipe !== undefined ? recipe : dishes[dishIndex].recipe,
      weather_condition: weather_condition !== undefined ? weather_condition : dishes[dishIndex].weather_condition,
      image_url: image_url !== undefined ? image_url : dishes[dishIndex].image_url,
      is_active: is_active !== undefined ? is_active : dishes[dishIndex].is_active,
      updated_at: Date.now()
    };

    if (writeData(dishesFile, dishes)) {
      res.json({ message: '菜品更新成功', dish: dishes[dishIndex] });
    } else {
      res.status(500).json({ error: '更新菜品失败' });
    }
  } catch (error) {
    logger.error('更新菜品错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 删除菜品
app.delete('/api/dishes/:id', authenticateToken, (req, res) => {
  try {
    if (req.user.role !== 'kitchen') {
      return res.status(403).json({ error: '权限不足' });
    }

    const dishId = parseInt(req.params.id);
    const dishes = readData(dishesFile);
    const dishIndex = dishes.findIndex(d => d.id === dishId);

    if (dishIndex === -1) {
      return res.status(404).json({ error: '菜品不存在' });
    }

    dishes.splice(dishIndex, 1);

    if (writeData(dishesFile, dishes)) {
      res.json({ message: '菜品删除成功' });
    } else {
      res.status(500).json({ error: '删除菜品失败' });
    }
  } catch (error) {
    logger.error('删除菜品错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 创建订单
app.post('/api/orders', authenticateToken, (req, res) => {
  try {
    if (req.user.role !== 'customer') {
      return res.status(403).json({ error: '权限不足' });
    }

    const { items, user_info, total_price } = req.body;

    if (!items || !user_info || !total_price) {
      return res.status(400).json({ error: '订单信息不完整' });
    }

    const orders = readData(ordersFile);
    const newOrder = {
      id: orders.length > 0 ? Math.max(...orders.map(o => o.id)) + 1 : 1,
      order_id: uuidv4(),
      items,
      user_info,
      total_price: parseFloat(total_price),
      status: 'pending',
      created_at: Date.now(),
      updated_at: null,
      estimated_time: null
    };

    orders.push(newOrder);

    if (writeData(ordersFile, orders)) {
      res.status(201).json({ message: '订单创建成功', order: newOrder });
    } else {
      res.status(500).json({ error: '保存订单失败' });
    }
  } catch (error) {
    logger.error('创建订单错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 获取所有订单
app.get('/api/orders', authenticateToken, (req, res) => {
  try {
    const orders = readData(ordersFile);
    
    // 根据用户角色过滤订单
    let filteredOrders;
    if (req.user.role === 'kitchen') {
      filteredOrders = orders;
    } else {
      filteredOrders = orders.filter(order => 
        order.user_info && order.user_info.username === req.user.username
      );
    }

    res.json(filteredOrders);
  } catch (error) {
    logger.error('获取订单列表错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 更新订单状态
app.put('/api/orders/:id', authenticateToken, (req, res) => {
  try {
    if (req.user.role !== 'kitchen') {
      return res.status(403).json({ error: '权限不足' });
    }

    const orderId = parseInt(req.params.id);
    const { status, estimated_time } = req.body;

    const orders = readData(ordersFile);
    const orderIndex = orders.findIndex(o => o.id === orderId);

    if (orderIndex === -1) {
      return res.status(404).json({ error: '订单不存在' });
    }

    // 更新订单信息
    orders[orderIndex] = {
      ...orders[orderIndex],
      status: status || orders[orderIndex].status,
      estimated_time: estimated_time !== undefined ? estimated_time : orders[orderIndex].estimated_time,
      updated_at: Date.now()
    };

    if (writeData(ordersFile, orders)) {
      res.json({ message: '订单更新成功', order: orders[orderIndex] });
    } else {
      res.status(500).json({ error: '更新订单失败' });
    }
  } catch (error) {
    logger.error('更新订单错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 获取用户信息
app.get('/api/user', authenticateToken, (req, res) => {
  try {
    const users = readData(usersFile);
    const user = users.find(u => u.id === req.user.id);

    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }

    // 不返回密码
    const { password, ...userWithoutPassword } = user;
    res.json(userWithoutPassword);
  } catch (error) {
    logger.error('获取用户信息错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// ==================== 健康检查 ====================
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    message: '本地文件存储版本运行正常',
    timestamp: new Date().toISOString()
  });
});

// ==================== 404处理 ====================
app.use((req, res) => {
  res.status(404).json({ error: '接口不存在' });
});

// ==================== 启动服务器 ====================
app.listen(PORT, () => {
  logger.info(`服务器启动成功，端口: ${PORT}`);
  logger.info(`数据存储目录: ${dataDir}`);
  logger.info(`访问地址: http://localhost:${PORT}`);
});

module.exports = app;